package com.tywj.lib.core.common.util

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import com.blankj.utilcode.util.PhoneUtils
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/7
 *     desc   : 手机工具类
 *     version: 1.0
 * </pre>
 */
object PhoneUtil {

    /**
     * 手机号中间4位使用*替换
     * @param phone
     * @return
     */
    fun midleReplaceStar(phone: String): String? {
        var result: String? = null
        if (!TextUtils.isEmpty(phone)) {
            result = if (phone.length < 7) {
                phone
            } else {
                val start = phone.substring(0, 3)
                val end = phone.substring(phone.length - 4, phone.length)
                val sb = StringBuilder()
                sb.append(start).append("****").append(end)
                sb.toString()
            }
        }
        return result
    }

    /**
     * 电话号码分段显示 如：xxx xxxx xxxx
     * @param s
     */

    fun mobileSegmentShow(s: String): String? {
        val addString = " "
        var finalString: String? = ""
        var index = 0
        val telString = s.replace(" ", "")
        if (index + 3 < telString.length) {
            finalString += telString.substring(index, index + 3) + addString
            index += 3
        }
        while (index + 4 < telString.length) {
            finalString += telString.substring(index, index + 4) + addString
            index += 4
        }
        finalString += telString.substring(index, telString.length)
        return finalString
    }

    /**
     * 拨打电话，如果权限被拒跳转至拨号界面
     * 需要在AndroidManifest文件中配置权限'android.permission.CALL_PHONE'
     * @param phone 手机号
     */
    @SuppressLint("MissingPermission")
    fun call(context: Context, phone: String) {
        AndPermission.with(context)
            .runtime()
            .permission(Permission.CALL_PHONE)
            .onGranted {
                PhoneUtils.call(phone)
            }
            .onDenied {
                PhoneUtils.dial(phone)
            }
            .start()
    }
}